Navigation

  • index
  • next |
  • previous |
  • PyHowTo documentation »
  • Basic »
  • Searches »

Table of Contents

Python v3.7 HowTos:

  • ----------------
  • Recursion
  • Backtracking
  • Dynamic Programming
  • Greedy
  • Sort
  • Binary Search
  • Depth First Search [DFS]
  • Breadth First Search [BFS]
  • Binary Search Tree [BST]
  • ----------------
  • Array
  • String
  • Heap
  • Stack
  • Queue
  • Tree
  • Linked List
  • Hash Table
  • Bit Manipulation
  • Two Pointers
  • Math
  • Decorator
  • ----------------
  • Basic
  • Intermediate
  • Advanced
  • Interview
  • ----------------
  • Spark
  • Tkinter
  • Turtle
  • Games
  • Web
  • ----------------
  • About
  • History

Previous topic

Searches

Next topic

Binary search in SORTED array (only)

Quick search

Binary searchΒΆ

Write a python program for Binary Search.
Binary Search:
In computer science, a binary search or half-interval search
algorithm finds the position of a target value within a sorted array.
The binary search algorithm can be classified as a dichotomies
DIVIDE-AND-CONQUER search algorithm and executes in logarithmic time.
Test Data :
binary_search([1,2,3,5,8], 6) -> False
binary_search([1,2,3,5,8], 5) -> True
def binary_search(A, N):

       first = 0
       last = len(A)-1
       found = False

       while first <= last and not found:

               mid = (first + last)//2

               if A[mid] == N :
                       found = True
               else:
                       if N < A[mid]:
                               last = mid - 1
                       else:
                               first = mid + 1
       return found

print(binary_search([1, 2, 3, 5, 8], 6))                       # False
print(binary_search([1, 2, 3, 5, 8], 5))                       # True

See also

https://www.w3resource.com/python-exercises/data-structures-and-algorithms/python-search-and-sorting-exercise-1.php

Navigation

  • index
  • next |
  • previous |
  • PyHowTo documentation »
  • Basic »
  • Searches »
© Copyright 2020, Sergiy Zaytsev, szaytsev@hotmail.com. Created using Sphinx 2.3.0.